﻿import kliment.display.SpriteBtn;

/**
 * ...
 * @author	Kliment
 * @version	1.0.5
 */
class kliment.controls.SimpleButton extends SpriteBtn {
	private var _intervalID:Number;
	private var _intervalDoubleClickID:Number;
	private var _repeatDalay:Number = 100;
	private var _doubleClickDalay:Number = 200;
	private var _clickCount:Number = 0;
	
	private var _isMove:Boolean;
	public var doubleClickEnabled:Boolean = false;
	
	public var onClick:Function;
	public var onDoubleClick:Function;
	public var onMousePress:Function;
	public var onMouseReleaseOutside:Function;
	public var onMousePressing:Function;
	
	public function SimpleButton(target_mc:MovieClip, repeatDalay:Number, doubleClickDalay:Number) {
		super(target_mc);
		if (!isNaN(repeatDalay))
			_repeatDalay = repeatDalay;
		if (!isNaN(doubleClickDalay))
			_doubleClickDalay = doubleClickDalay;
		_init();
	}
	
	private function _init():Void {
		addListener(this);
	}
	
	public function setFocus():Void {
		_target_mc.gotoAndPlay('over');
	}
	
	public function resetFocus():Void {
		_target_mc.gotoAndPlay('out');
	}
	
	private function onPress():Void {
		if (_clickCount < 1) {
			_isMove = false;
			onMousePress(this);
			clearInterval(_intervalID);
			_intervalID = setInterval(this, '_onMouseDown', _repeatDalay * 2);
		}
	}
	
	private function onMouseMove():Void {
		if (doubleClickEnabled) 
			_isMove = true;
	}
	
	private function _onMouseDown():Void {
		_clickCount = 0;
		clearInterval(_intervalDoubleClickID);
		clearInterval(_intervalID);
		_intervalID = setInterval(this, 'onMousePressing', _repeatDalay, this);
	}
	
	private function onRelease():Void {
		clearInterval(_intervalID);
		if (doubleClickEnabled) {
			if (_isMove)
				_doubleClickHandler();
			++_clickCount;
			switch (_clickCount) {				
				case 1:
					clearInterval(_intervalDoubleClickID);
					_intervalDoubleClickID = setInterval(this, '_doubleClickHandler', _doubleClickDalay);
				break;
				
				case 2:
					_doubleClickHandler();
				break;
			}
		} else {
			onClick(this);
		}
	}
	
	private function _doubleClickHandler():Void {
		clearInterval(_intervalDoubleClickID);
		if (_clickCount < 2 || _isMove) 
			onClick(this);
		else 
			onDoubleClick(this);
		_clickCount = 0;
		_isMove = false;
	}
	
	private function onRollOver():Void {
		setFocus();
	}
	
	private function onRollOut():Void {
		resetFocus();
	}
	
	private function onReleaseOutside():Void {
		clearInterval(_intervalID);
		onRollOut();
		onMouseReleaseOutside(this);
	}
}